#!/bin/bash

ex=$1 # exec
po=$2 # policy
tr=$3 # trace file path
cs=$4 # lru cache size

if [ ! -x "build/bin/${ex}" ]; then
    echo $ex 'is not executable'
    exit 1
fi

fn=${tr##*/}  # trace file name
fn=${fn%.csv} # trim file name

od="output/${fn}/${po}" # output dir
mkdir -p "${od}"

# get max cores
if [ -f 'build/.max_core' ]; then
    max_core=$(cat build/.max_core)
else
    # get total core number from lscpu
    ls_core=$(lscpu -p=CORE | grep -v \# -c)
    max_core=$((${ls_core:-7} - 1))
    echo $max_core >'build/.max_core'
fi

# get cores
if [ -f 'build/.cur_core' ]; then
    cur_core=$(cat build/.cur_core)
    if [ $cur_core -le 0 -o $cur_core -ge $max_core ]; then
        cur_core=$max_core
    fi
else
    cur_core=$max_core
fi

of="${od}/${cs}.txt" # output file

# args shift
shift 4

echo "[${cur_core}] ./cas exec \"${ex}\" 0 ${po} ${tr} ${cs} $@ >\"${of}\""
# nohup
taskset -c $cur_core nohup ./cas exec "${ex}" 0 $po ${tr} ${cs} $@ >"${of}" 2>&1 &

let "cur_core--"
if [ $cur_core -le 0 ]; then
    cur_core=$max_core
fi
echo $cur_core >'build/.cur_core'
